<template>
  <div>
    <div class="pageTitleWhole">
      <div style="overflow: hidden">
        <a style="margin-right: 20px; margin-bottom: 15px; float: left;"><router-link :to="`/financialCenter/${page.isPayOrRecevie?'payableBillOfChuang':'receivableBillOfChuang'}?f=1`"><a-icon type="left" />返回</router-link></a>
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link :to="`/financialCenter/${page.url}`">应{{page.isPayOrRecevie?'付':'收'}}账单</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>账单详情</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
    </div>
    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="船名">
              <a-input v-model="searchForm.shipName"/>
            </a-form-item>
            <a-form-item label="航次">
              <a-input v-model="searchForm.voyageNumber"/>
            </a-form-item>
            <a-form-item label="费用类型">
              <a-select v-model="searchForm.feeTypeId" class="selectInputWidth">
                <a-select-option value>请选择</a-select-option>
                <a-select-option v-for="(v,k) in feeList" :key="k" :value="v.id">{{v.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="!page.isPayOrRecevie" label="结算对象">
              <a-input v-model="searchForm.custName"/>
            </a-form-item>
            <a-form-item v-if="!searchForm.statusTab" label="状态">
              <a-select v-model="searchForm.status" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option :key="1">未对账</a-select-option>
                <a-select-option :key="2">已对账</a-select-option>
                <a-select-option :key="3">已结清</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="日期">
              <a-range-picker :value="searchForm.dateRange" @change="onDateChange">
                <a-icon slot="suffixIcon" type="calendar" />
              </a-range-picker>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="exportExcel">导出Excel</a-button>
            </a-form-item>
            <a-form-item v-if="page.status === '1'">
              <a-button type="primary" @click="removeBills">移出账单</a-button>
            </a-form-item>
          </a-form>
        </a-col>

        <a-col :span="24" style="margin-top:24px;">
          <a-table :row-selection="page.status === '1'?{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange}:null"
            :columns="columns"
            :loading="loading"
            :data-source="tableData"
            :pagination="pagination"
            row-key="id"
          >
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <span slot="customTitle1">
              应{{page.isPayOrRecevie?'付':'收'}}金额（元）
            </span>
            <span slot="customTitle2">
              应{{page.isPayOrRecevie?'付':'收'}}结算对象
            </span>
          </a-table>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import {queryFeeTypeList} from '@/api'
import {commonExport} from '@/api/request'
import {queryJCVoyageBillCostList, cancelFromBill} from '@/api/financialCenter'

const defaultSearchForm = (feeType, billId) => ({
  feeType,
  billId,
  status,
  statusTab: status,
  custName: '',
  shipName: '',
  voyageNumber: '',
  feeTypeId: '',
  searchStartTime: null,
  searchEndTime: null,
  dateRange: [null, null]
})

export default {
  props: ['id'],
  data () {
    const columnsWhole = [
      {
        title: '序号',
        width: 60,
        scopedSlots: {customRender: 'rn'}
      },
      {
        title: '船名',
        ellipsis: true,
        dataIndex: 'shipName'
      },
      {
        title: '航次',
        dataIndex: 'voyageNumber',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '费用类型',
        dataIndex: 'feeName'
      },
      {
        slots: { title: 'customTitle1' },
        dataIndex: 'amount'
      },
      {
        slots: { title: 'customTitle2' },
        dataIndex: 'custName',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '日期',
        dataIndex: 'costTime',
        width: 115
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 90,
        customRender: (text, record, index) => {
          return text === 1 ? <span style="color: red">未对账</span> : (text === 2 ? <span style="color: green">已对账</span> : (text === 3 ? '已结清' : ''))
        },
        _needName: true
      }
    ]

    return {
      // 页面区分信息
      page: {
        status: '', // 1未结清，2已结清
        url: '',
        isPayOrRecevie: true // t付 f收
      },
      feeList: [],
      holderList: [],
      portList: [],
      searchForm: defaultSearchForm(''),
      columns: columnsWhole,
      loading: false,
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      selectedRowKeys: []
    }
  },
  methods: {
    onChangeStatus (key) {
      this.searchForm = defaultSearchForm(key)
      this.handleSubmit1()
    },
    initFeeTypeRequest (e) {
      queryFeeTypeList(e)
        .then(res => {
          this.feeList = res.data
        })
        .catch(rs => {})
    },
    onDateChange (date, dataStr) {
      this.searchForm.searchStartTime = dataStr[0]
      this.searchForm.searchEndTime = dataStr[1]
      this.searchForm.dateRange = [date[0], date[1]]
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.selectedRowKeys = []
      this.loading = true
      queryJCVoyageBillCostList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      })
    },
    exportExcel () {
      commonExport('/bill/exportJCVoyageBillCostList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns.map(v => {
          if (v.dataIndex === 'amount') {
            return {...v, title: `应${this.page.isPayOrRecevie ? '付' : '收'}金额（元）`}
          } else if (v.dataIndex === 'custName') {
            return {...v, title: `应${this.page.isPayOrRecevie ? '付' : '收'}结算对象`}
          } else {
            return v
          }
        })
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    removeBills () {
      if (!this.$root._bc.removeBill) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请先选择费用明细')
      } else {
        cancelFromBill({
          billCostIds: this.selectedRowKeys,
          billId: this.id
        }).then(rsp => {
          this.$message.success('移除成功')
          this.handleSubmit()
        })
      }
    }
  },
  created () {
    const url = this.$route.meta.selectKeyUrl
    this.page.url = url
    this.page.isPayOrRecevie = !!~url.indexOf('pay')

    let feeType = this.page.isPayOrRecevie ? 2 : 1
    this.searchForm = defaultSearchForm(feeType, this.id)

    this.page.status = this.$route.query.status + ''

    // 供应商中心所有正常状态的应付费用类型
    this.initFeeTypeRequest({
      status: 1,
      belongCompany: 'JIA_CHUANG',
      feeType
    })
  },
  mounted () {
    this.handleSubmit()
  }
}
</script>

<style lang="less" scoped>

</style>
